package config

import (
	"log"
	"os"

	"gopkg.in/yaml.v3"
)

// EndpointConfig 端点配置
type EndpointConfig struct {
	Path    string `yaml:"path"`
	Enabled bool   `yaml:"enabled"`
}

// FalcoFilterConfig Falco过滤配置
type FalcoFilterConfig struct {
	MinPriority string   `yaml:"min_priority"` // 最小优先级，低于此优先级的告警将被过滤
	ExcludeRules []string `yaml:"exclude_rules"` // 要排除的规则列表
}

type ServerConfig struct {
	Port     int    `yaml:"port"`
	LogLevel string `yaml:"log_level"`
}

type DitingConfig struct {
	URL       string                    `yaml:"url"`
	Endpoints map[string]EndpointConfig `yaml:"endpoints"`
	FalcoFilter FalcoFilterConfig       `yaml:"falco_filter"` // Falco过滤配置
}

type Config struct {
	Server ServerConfig `yaml:"server"`
	Diting DitingConfig `yaml:"diting"`
}

// 全局配置变量
var Global Config

// Load 从指定文件路径加载 YAML 配置
func Load(configFile string) error {
	data, err := os.ReadFile(configFile)
	if err != nil {
		return err
	}

	if err := yaml.Unmarshal(data, &Global); err != nil {
		return err
	}

	// 设置默认值
	if Global.Server.Port == 0 {
		Global.Server.Port = 8082
	}

	log.Printf("✅ Agent配置加载成功: 服务监听端口 %d", Global.Server.Port)
	log.Printf("📤 告警将发送到: %s", Global.Diting.URL)

	// 打印启用的端点
	log.Printf("🔌 启用的端点:")
	for name, endpoint := range Global.Diting.Endpoints {
		if endpoint.Enabled {
			log.Printf("   - %s: %s (已启用)", name, endpoint.Path)
		} else {
			log.Printf("   - %s: %s (已禁用)", name, endpoint.Path)
		}
	}

	// 打印Falco过滤配置
	if Global.Diting.FalcoFilter.MinPriority != "" {
		log.Printf("🔍 Falco最小优先级过滤: %s", Global.Diting.FalcoFilter.MinPriority)
	}
	if len(Global.Diting.FalcoFilter.ExcludeRules) > 0 {
		log.Printf("🚫 Falco排除规则:")
		for _, rule := range Global.Diting.FalcoFilter.ExcludeRules {
			log.Printf("   - %s", rule)
		}
	}

	return nil
}